package com.bp.hearthealth.pulse.lnapps.ads.admob.open_ad

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.text.TextUtils
import com.bp.hearthealth.pulse.lnapps.BpApplication
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.MultiLanguageUtils
import com.bp.hearthealth.pulse.lnapps.bp_utils.SpUtils
import com.bp.hearthealth.pulse.lnapps.notification.ForegroundActivityManager
import java.util.Locale

class AppForegroundHelper {
    private var currentActivity: Activity? = null
    var firstActivityCreated = false
    var hasSavedState = false

    fun init(application: Application) {
        application.registerActivityLifecycleCallbacks(activityLifecycleCallbacks)
    }

    private val activityLifecycleCallbacks = object : Application.ActivityLifecycleCallbacks {
        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
            //获取Activity弱引用
            ForegroundActivityManager.setCurrentActivity(activity)

            val language = SpUtils.getString(BpApplication.context, Constants.LOCALE_LANGUAGE)
            val country = SpUtils.getString(BpApplication.context, Constants.LOCALE_COUNTRY)
            if (!TextUtils.isEmpty(language) && !TextUtils.isEmpty(country)) {
                //强制修改应用语言
                if (!MultiLanguageUtils.isSameWithSetting(activity)) {
                    val locale = Locale(language, country)
                    MultiLanguageUtils.changeAppLanguage(activity, locale, false)
//                    activity.recreate()
                }
            }
            if (firstActivityCreated) {
                return
            }
            firstActivityCreated = true
            hasSavedState = savedInstanceState != null
        }

        override fun onActivityStarted(activity: Activity) {
            if (!BpApplication.adMobOpenAdManager!!.isShowingAd) {
                currentActivity = activity
            }
        }

        override fun onActivityResumed(activity: Activity) {
            //获取Activity弱引用
            ForegroundActivityManager.setCurrentActivity(activity)
            //设置当前Active状态为true
            ForegroundActivityManager.setActive(true)
        }

        override fun onActivityStopped(activity: Activity) {

        }

        override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

        override fun onActivityDestroyed(activity: Activity) {}

        override fun onActivityPaused(activity: Activity) {
            //设置当前Active状态为false
            ForegroundActivityManager.setActive(false)
        }
    }

    fun getCurrentActivity(): Activity? {
        return currentActivity
    }
}
